<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>before中使用attr</title>
</head>
<body>
    <div class="has-before" data-contents="前置内容">
        这是内容
    </div>
    <input id="toggleBtn" type="button" value="切换内容">
</body>
<script>
    const hasBeforeDom = document.querySelector('.has-before');
    const toggleBtn = document.querySelector('#toggleBtn');
    toggleBtn.onclick = () => {
        console.dir(hasBeforeDom);
        if (hasBeforeDom.hasAttribute('data-contents')) {
            hasBeforeDom.removeAttribute('data-contents');
        } else {
            hasBeforeDom.setAttribute('data-contents', '前置内容');
        }
    }
</script>
<style>
    .has-before::before {
        content: attr(data-contents);
    }
</style>
</html>